<template>
	<view class="page">
		<u-form ref="uForm">
			<u-form-item :leftIconStyle="{ color: '#888', fontSize: '32rpx' }" label-width="120" label="帐号：" prop="name">
				<u-input placeholder="请输入帐号" type="text" v-model="username"></u-input>
			</u-form-item>
			<u-form-item label="密码：" label-width="120" prop="password">
				<u-input :password-icon="true" type="password" placeholder="请输入密码" v-model="password"></u-input>
			</u-form-item>
		</u-form>
		<view class="btn">
			<u-button type="primary" @click="bindLogin">登录</u-button>
		</view>
		<view v-show="showReg == '1'" class="none_user">
			<span class="none_user_text" @click="register">还没有账号？去注册</span>
		</view>
	</view>
</template>

<script>
import { getShowRegister } from '@/api/common.js';
export default {
	components: {},
	data() {
		return {
			providerList: [],
			username: '',
			password: '',
			showReg: '0',
		};
	},
	onShow() {
		this.getShowRegisterConfig();
		this.getUserInfo();
	},
	onHide() {},
	methods: {
		// 获取注册按钮显示配置
		async getShowRegisterConfig() {
			let rs = await this.$api.common.getShowRegister({});
			if (rs.code == 200) {
				this.showReg = rs.data;
			}
		},
		// 注册
		register() {
			uni.navigateTo({
				url: '/pages/login/register',
			});
		},
		// 获取本地是否存储信息
		async getUserInfo() {
			// 如果账号和密码没有自动填充，获取缓存
			if (!this.username) {
				const userInfo = (await uni.getStorageSync('loginUserInfo')) || {};
				if (Object.keys(userInfo).length > 0) {
					this.username = userInfo.username;
					this.password = userInfo.password;
				}
			}
		},
		async bindLogin() {
			/**
			 * 客户端对账号信息进行一些必要的校验。
			 * 实际开发中，根据业务需要进行处理，这里仅做示例。
			 */
			if (this.username.length < 5) {
				uni.showToast({
					icon: 'none',
					title: '账号最短为 5 个字符',
				});
				return;
			}
			if (this.password.length < 6) {
				uni.showToast({
					icon: 'none',
					title: '密码最短为 6 个字符',
				});
				return;
			}
			const data = {
				username: this.username,
				password: this.password,
			};

			// 是否返回上一个退出的页面
			let isBack = (await uni.getStorageSync('isBack')) || 0;
			let res = await this.$store.dispatch('Login', data);
			if (res.code === 200) {
				uni.removeStorageSync('isShowModal');
				uni.removeStorageSync('onLaunch');
				let auth = await this.$store.dispatch('getAuth');
				if (auth.code === 200) {
					// 记录上一次退出的页面，登录后再返回
					if (isBack == 1) {
						uni.navigateBack();
					} else {
						uni.reLaunch({
							url: '/pages/main/main',
						});
					}
					// 登录后再设置为0
					uni.setStorageSync('isBack', 0);
				}
			}
		},
	},
};
</script>

<style lang="scss" scoped>
.u-form {
	padding: 15px 0;
	.u-form-item {
		padding: 10px;
		background: #fff;
	}
}

.btn {
	padding: 0 15px;
}
.none_user {
	margin-top: 5px;
	text-align: right;
	padding-right: 20px;
	color: #00aaff;
}
.none_user_text {
	border-bottom: 1px solid #00aaff;
}
</style>
